import axios from 'axios'
import { Message, MessageBox,Alert } from 'element-ui'
import store from '../store'
import { getToken } from '@/utils/auth'
import router from '@/router/index.js'
import {version} from '@/utils/version.js'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 120*1000 ,// 请求超时时间
})

// request拦截器
service.interceptors.request.use(config => {
  if (getToken()) {
    // config.headers['Authorization'] = 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjIyOTksImlzcyI6Imh0dHA6Ly93d3cubW9yZXN1dGVzdC5jb20vdXNlckF1dGgvZ2V0U2hvcFRva2VuIiwiaWF0IjoxNTc2MDI1OTE2LCJleHAiOjE1NzYwNTQ3MTYsIm5iZiI6MTU3NjAyNTkxNiwianRpIjoiNjBCRG5RWGtvMjJkamNTSSJ9.c924tj5-mspSAAD09eqqerANZ3PmxIo4hQ8i7tiHm7M';
    config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    let token = getToken();
    config.data = Object.assign({token:token,appVersion:version,appFrom:'p'}, config.data);
  }else{
    config.data = Object.assign({appVersion:version,appFrom:'p'}, config.data);
  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
  /**
  * code为非200是抛错 可结合自己业务进行修改
  */
    const res = response.data;
    if(res.code == 800001){
       MessageBox.alert('当前不是最新版本，请刷新页面更新版本', '版本更新', {
          confirmButtonText: '确定',
          callback: action => {
             window.location.reload(true)
          }
        });
     }else if(res.code == 401 || res.code==60401){
//       Message({
//         message: res.msg,
//         type: 'warning ',
//         duration: 3 * 1000
//       });
      store.dispatch('LogOut').then(() => {
          router.push({path:'/login'})
//         location.reload() // 为了重新实例化vue-router对象 避免bug
      })
    }else if(res.code == 10000 || res.code == 10001){
      return Promise.reject(response.data)
    }else if (res.code !== 200) {
        Message({
          message: res.msg,
          type: 'warning',
          duration: 3 * 1000
        });
      return Promise.reject(response.data)
    } else {
      return response.data.content
    }
  },
  error => {
    let rej = error.response.data;
    if (rej.code !== 60016 && rej.code !== 666666){ //批量发货出错，或者物流单号出错，不弹错误提示单独处理
      Message({
        message: rej.msg,
        type: 'warning',
        duration: 3 * 1000
      });
      // token问题，全部登出;
      // if (rej.code === 46409 || rej.code === 46408 || rej.code === 46407) {
      //   Message({
      //     message: '你已被登出，请重新登录',
      //     type: 'error',
      //     duration: 3 * 1000
      //   });
      //   store.dispatch('FedLogOut').then(() => {
      //     //todo,去摩塑网登录
      //     // window.location.href="http://www.moresutest.com/dist/index.html#login?redirect=CRM"
      //   })
      // }
    }
    return Promise.reject(rej)
  }
);

export default service
